package com.snail.auth.action;

import com.alibaba.fastjson.JSON;
import com.common.ResultCodeEnum;
import com.common.ResultUtil;
import com.common.entity.BaseController;
import com.common.util.StringUtil;
import com.common.util.http.HttpUtil;
import com.snail.auth.entity.AuthOrg;
import com.snail.auth.entity.AuthRole;
import com.snail.auth.entity.AuthUser;
import com.snail.auth.service.AuthOrgService;
import com.snail.auth.service.AuthRoleService;
import com.snail.auth.service.AuthUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "用户管理 用户信息")
@RestController
@RequestMapping("auth/user")
public class AuthUserController extends BaseController {
    @Autowired
    private AuthUserService userService;
    @Autowired
    private AuthOrgService deptService;
    @Autowired
    private AuthRoleService roleService;

    @ApiOperation(value = "用户信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "组织部门Id", dataType = "long", paramType = "query")
    })
    @GetMapping(value = "/list")
    public Map<String, Object> list() {
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", request.getParameter("orgId"));
        List<AuthUser> users = userService.listByHql(params);
        return ResultUtil.result(users);
    }

    @GetMapping(value = "/one/{id}")
    public Map<String, Object> detail(@PathVariable Long id) {
        AuthUser user = userService.getByKey(id);
        return ResultUtil.result(user);
    }

    @PostMapping
    public Map<String, Object> save(@RequestBody String requestJSON) {
        boolean isAdd = false;
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> requestMap = JSON.parseObject(requestJSON);
        Map<String, Object> userMap = JSON.parseObject(requestMap.get("user").toString());
        Map<String, Object> orgMap = JSON.parseObject(requestMap.get("org").toString());
        AuthUser user = new AuthUser();
        if (requestMap.containsKey("userId") && !StringUtil.isEmpty(requestMap.get("userId"))) {
            user = userService.getByKey(Long.valueOf(requestMap.get("userId").toString()));
        } else {
            isAdd = true;
            user.setSalt(UUID.randomUUID().toString());
            if (StringUtil.isEmpty(user.getPassword())) {
                user.setPassword("123456");
            }
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String EncryptedPassword = bCryptPasswordEncoder.encode(user.getPassword());
            user.setLoginName(userMap.get("loginName").toString());
            user.setPassword(EncryptedPassword);
            user.setAccountState(4);
            user.setIsAccountNonExpired(1);
            user.setIsAccountNonLocked(1);
            user.setIsEnabled(1);
            user.setFlag(0);
        }
        user.setName(userMap.get("name").toString());
        if (!StringUtil.isEmpty(userMap.get("phone"))) {
            user.setPhone(userMap.get("phone").toString());
        }
        if (!StringUtil.isEmpty(userMap.get("expireDate"))) {
            if (userMap.get("expireDate").toString().matches("\\d+")) {
                user.setExpireDate(new java.sql.Date(Long.valueOf(userMap.get("expireDate").toString()) + 8 * 3600 * 1000));
            } else {
                try {
                    Date date = new SimpleDateFormat("yyyy-MM-dd").parse(userMap.get("expireDate").toString());//默认取回的是UTC时间，需要加8小时转北京时间
                    user.setExpireDate(new java.sql.Date(date.getTime() + 24 * 3600 * 1000));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }else{//默认1年有效期
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.YEAR,1);
            user.setExpireDate(new java.sql.Date(cal.getTimeInMillis()));
        }
        if (!StringUtil.isEmpty(orgMap.get("id"))) {
            AuthOrg org = deptService.getByKey(Long.valueOf(orgMap.get("id").toString()));
            user.setOrg(org);
            result.put("orgId", orgMap.get("id"));
        }
        if (!StringUtil.isEmpty(userMap.get("isLeader"))) {
            user.setIsLeader(Integer.valueOf(userMap.get("isLeader").toString()));
        }
        if (!StringUtil.isEmpty(userMap.get("duty"))) {
            user.setDuty(userMap.get("duty").toString());
        }
        userService.save(user);

        Map<String,Object> params = new HashMap<>();
        params.put("id", user.getLoginName());
        params.put("displayName", user.getName());
        params.put("password", user.getPassword());
        if (!StringUtil.isEmpty(requestMap.get("roleIds"))) {
            List<AuthRole> roles = new ArrayList<>();
            if (requestMap.get("roleIds").toString().contains(",")) {
                String[] roleIds = requestMap.get("roleIds").toString().split(",");
                for (String roleId : roleIds) {
                    if (!StringUtil.isEmpty(roleId)) {
                        AuthRole role = roleService.getByKey(Long.valueOf(roleId));
                        roles.add(role);
                    }
                }
            } else {
                AuthRole role = roleService.getByKey(Long.valueOf(requestMap.get("roleIds").toString().trim()));
                roles.add(role);
            }
            user.setRoles(roles);
        }
        userService.save(user);
        result.put("userId", user.getId());
        return ResultUtil.result(result);
    }

    /**
     * 检查登录账号是否被占用
     */
    @GetMapping("/check/occupy")
    public Map<String, Object> isOccupy(@RequestParam String loginName) {
        boolean result = false;
        AuthUser user = userService.findByLoginName(loginName);
        if (user != null) {
            result = true;
        }
        return ResultUtil.result(result);
    }

    /**
     * 密码重置
     */
    @PutMapping(value = "reset/{id}")
    public Map<String, Object> reset(@PathVariable Long id) {
        AuthUser entity = userService.getByKey(id);
        String newPass = request.getParameter("pass");
        if (!StringUtil.isEmpty(newPass)) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String EncryptedPassword = bCryptPasswordEncoder.encode(newPass);
            entity.setPassword(EncryptedPassword);
            userService.save(entity);
        }
        return ResultUtil.result();
    }

    /**
     * 账号锁定
     */
    @PatchMapping(value = "lock/{id}")
    public String lock(@PathVariable Long id) {
        AuthUser entity = userService.getByKey(id);
        userService.save(entity);
        return entity.getId().toString();
    }

    /**
     * 账号解锁
     */
    @PatchMapping(value = "unlock/{id}")
    public String unlock(@PathVariable Long id) {
        AuthUser entity = userService.getByKey(id);
        userService.save(entity);
        return entity.getId().toString();
    }

    @ApiOperation(value = "密码修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long", paramType = "path")
            , @ApiImplicitParam(name = "yuanPass", value = "原密码", dataType = "string", paramType = "query")
            , @ApiImplicitParam(name = "newPass", value = "新密码", dataType = "string", paramType = "query")
    })
    @PutMapping(value = "/{id}/pwdalter")
    public Map pwdalter(@PathVariable Long id) {
        AuthUser user = userService.getByKey(id);
        String yuanPass = request.getParameter("yuanPass");
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String yuanPassE = bCryptPasswordEncoder.encode(yuanPass);

        if (yuanPassE.equals(user.getPassword())) {
            String newPass = request.getParameter("newPass");
            user.setPassword(bCryptPasswordEncoder.encode(newPass));
            userService.save(user);
            return ResultUtil.result();
        } else {
            return ResultUtil.result(ResultCodeEnum.RESULT_ERROR_PWD);
        }
    }

    /**
     * 删除指定用户
     */
    @DeleteMapping(value = "/{id}")
    public Map<String, Object> del(@PathVariable Long id) {
        userService.del(id);
        return ResultUtil.result();
    }

}
